// canvasImg/canvasImg.js
Page({
  data: {
    canvas:'',
    ctx:'',
    isAutoPicture:!1,
  },
  onLoad: function (options) {

  },
  onReady: function () {
    wx.createSelectorQuery().select("#canvas")
    .fields({ node: true, size: true })
    .exec(this.init.bind(this))
  },
  init:function(res){
    let canvas=res[0].node;
    let width=res[0].width,height=res[0].height;
    const dpr = wx.getSystemInfoSync().pixelRatio;//获取设备像素比
    this.data.canvas=canvas;
    console.log("size",width,height);
    this.data.ratio=width/750;
    this.data.canvas_width=width,this.data.canvas_height=height;
    let ctx=res[0].node.getContext('2d');
    this.data.ctx=ctx;
    //console.log("system", wx.getSystemInfoSync());
    console.log(width * dpr,height * dpr);
    ctx.fillStyle="#FFF";ctx.fillRect(0, 0, width, height);
    canvas.width = width * dpr
    canvas.height = height * dpr
    ctx.scale(dpr, dpr)
    ctx.font="18px sans-serif";
    ctx.fillStyle="#48a2a2";
    ctx.fillText("开始",50,20);
    this.drawImage({src:'/images/mobile.png',x:140,y:160,width:470,height:392});
    ctx.font="20px sans-serif";
    ctx.fillStyle="#454545";
    this.textCenter({text:'欢迎加入妮兔嗨购商城',y:650});
    ctx.font="16px sans-serif";
    ctx.fillStyle='#666666';
    this.textCenter({text:"点击进入",y:720})
  },
  textCenter(obj){
    //以宽度为750px 的画布绘制
    let ctx=this.data.ctx;
    if(typeof obj != 'object'){ return obj}
    if(!ctx){console.error("请找到canvas 的getCentent('2d') 并传入赋值参数 ctx"); return 1 }
    let center = (this.data.canvas_width - ctx.measureText(obj.text).width)/2
    let y=Number((this.data.ratio*obj.y).toFixed(1))
    ctx.fillText(obj.text,center,y)
  },
  // 在宽度为750px 的画布上绘制图形
  drawImage(obj){
    if(typeof obj!= 'object'){ return obj}
    let img=this.data.canvas.createImage(),
    radio=this.data.canvas_width/750,
    ctx=this.data.ctx;
    if(!ctx){console.error("请找到canvas 的getCentent('2d') 并传入赋值参数 ctx");return 1; }
    let width=Number((obj.width*radio).toFixed(1)),
      height=Number((obj.height*radio).toFixed(1)),
      x=Number((obj.x*radio).toFixed(1)),
      y=Number((obj.y*radio).toFixed(1));
    img.src = obj.src;
    img.onload = () => {
      ctx.drawImage(img,x,y,width,height);
    }
  },
  handleSetting(e){
    var that = this;
    if (!e.detail.authSetting['scope.writePhotosAlbum']){
        wx.showModal({
            title: '警告',
            content: '不授权无法保存',
            showCancel: false
        })
        that.setData({
          isAutoPicture: true
        })
    }else{
        that.setData({
          isAutoPicture: false
        });
        that.saveImgBtn()
    }
  },
  saveImgBtn(){
    let e=this;
    wx.canvasToTempFilePath({
      x:0,y:0,width:750,height:900,destWidth:750,destHeight:900,
      canvas:this.data.canvas,
      success:(res)=>{
        let url=res.tempFilePath;
        if (!res.tempFilePath) {
          wx.showModal({
            title: '提示',
            content: '图片绘制中，请稍后重试',
            showCancel: false
          });
          return 1;
        }
        wx.saveImageToPhotosAlbum({
          filePath: url,
          success(res) {
            console.log(res);
            wx.showModal({
              title: '图片保存成功',
              content: '图片成功保存到相册了，去发圈噻~',
              showCancel: false,
              confirmText: '好哒',
              //confirmColor: '#72B9C3',
              success: function (res) {
                e.setData({isAutoPicture:!1})
                if (res.confirm) {
                  console.log('用户点击确定');
                }
              }
            })
          },fail:function(){
            e.setData({
              isAutoPicture:!0,
            })
            wx.showModal({
              title: '图片保存失败',
              content: '图片保存失败，请同意小程序保存到相册',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                }
              }
            })
          }
        })

      }
    })
  },
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})